from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from sqlalchemy.exc import ProgrammingError
from typing import Optional
from datetime import datetime

from database.connection import get_db
from database.models import SiteInfo
from models.site import SiteInfoCreate, SiteInfoUpdate, SiteInfoResponse
from routers.admin import verify_admin_permission

router = APIRouter(prefix="/site", tags=["网站设置"])


@router.get("/info", summary="获取网站基础信息")
async def get_site_info(db: Session = Depends(get_db)):
    """
    获取当前激活的网站基础信息
    若不存在激活记录，返回空数据结构
    """
    try:
        site = db.query(SiteInfo).filter(SiteInfo.is_active == True).order_by(SiteInfo.updated_at.desc()).first()
        if not site:
            return {
                "code": 200,
                "msg": "暂无站点信息",
                "data": {}
            }
        return {
            "code": 200,
            "msg": "获取成功",
            "data": SiteInfoResponse.from_orm(site)
        }
    except ProgrammingError:
        return {
            "code": 200,
            "msg": "站点信息表未初始化，请先创建数据库表",
            "data": {}
        }
    except Exception as e:
        return {
            "code": 500,
            "msg": f"获取站点信息失败: {str(e)}"
        }


@router.put("/info", summary="保存网站基础信息")
async def save_site_info(
    payload: SiteInfoUpdate,
    db: Session = Depends(get_db),
    admin_user = Depends(verify_admin_permission)
):
    """
    保存或更新网站基础信息（仅管理员）
    - 若存在激活记录：进行字段级更新
    - 若不存在：创建新记录并设为激活
    """
    try:
        current = db.query(SiteInfo).filter(SiteInfo.is_active == True).order_by(SiteInfo.updated_at.desc()).first()

        if current:
            update_data = payload.dict(exclude_unset=True)
            if not update_data:
                return {"code": 400, "msg": "未提供需要更新的字段"}
            update_data["updated_at"] = datetime.now()
            for field, value in update_data.items():
                setattr(current, field, value)
            db.commit()
            db.refresh(current)
            return {
                "code": 200,
                "msg": "更新成功",
                "data": SiteInfoResponse.from_orm(current)
            }
        else:
            create_payload = SiteInfoCreate(**payload.dict(exclude_unset=True))
            if not create_payload.site_name or not create_payload.site_name.strip():
                return {"code": 400, "msg": "网站名称不能为空"}
            new_site = SiteInfo(
                site_name=create_payload.site_name.strip(),
                site_description=create_payload.site_description,
                site_keywords=create_payload.site_keywords,
                logo_url=create_payload.logo_url,
                icp_number=create_payload.icp_number,
                contact_email=create_payload.contact_email,
                service_phone=create_payload.service_phone,
                company_address=create_payload.company_address,
                is_active=True,
                created_at=datetime.now(),
                updated_at=datetime.now()
            )
            db.add(new_site)
            db.commit()
            db.refresh(new_site)
            return {
                "code": 200,
                "msg": "创建成功",
                "data": SiteInfoResponse.from_orm(new_site)
            }
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"保存站点信息失败: {str(e)}"
        )


class LogoUpdatePayload(SiteInfoUpdate):
    """
    Logo 更新请求模型（复用 SiteInfoUpdate 结构，仅使用 logo_url）
    """
    pass


# @router.put("/logo", summary="更新站点Logo")
# async def update_logo(
#     payload: LogoUpdatePayload,
#     db: Session = Depends(get_db),
#     admin_user = Depends(verify_admin_permission)
# ):
#     """
#     更新站点 Logo（仅管理员）
#     接收 `logo_url`，写入当前激活记录；若不存在记录则创建
#     """
#     try:
#         if not payload.logo_url or not str(payload.logo_url).strip():
#             return {"code": 400, "msg": "logo_url 不能为空"}

#         current = db.query(SiteInfo).filter(SiteInfo.is_active == True).order_by(SiteInfo.updated_at.desc()).first()
#         if current:
#             current.logo_url = str(payload.logo_url).strip()
#             current.updated_at = datetime.now()
#             db.commit()
#             db.refresh(current)
#             return {"code": 200, "msg": "Logo 更新成功", "data": {"logo_url": current.logo_url}}
#         else:
#             new_site = SiteInfo(
#                 site_name="AIGD100",
#                 logo_url=str(payload.logo_url).strip(),
#                 is_active=True,
#                 created_at=datetime.now(),
#                 updated_at=datetime.now()
#             )
#             db.add(new_site)
#             db.commit()
#             db.refresh(new_site)
#             return {"code": 200, "msg": "Logo 已创建并设置", "data": {"logo_url": new_site.logo_url}}
#     except HTTPException:
#         raise
#     except Exception as e:
#         db.rollback()
#         return {"code": 500, "msg": f"更新站点Logo失败: {str(e)}"}
